package com.leyou.sms.mq;

import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsConfiguration;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;


import static com.leyou.common.mq.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.mq.MQConstants.Queue.SMS_VERIFY_CODE_QUEUE;
import static com.leyou.common.mq.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Slf4j
@Component
@EnableConfigurationProperties(value = SmsProperties.class)
public class SmsListener {

    @Autowired
    private SmsProperties prop;    //属性类

    @Autowired
    private SmsHelper smsHelper;   //发送短信工具类

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SMS_VERIFY_CODE_QUEUE),   //短信验证码队列
            exchange = @Exchange(name = SMS_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),  //消息服务交换机
            key = VERIFY_CODE_KEY                 //验证码的 Routing key
    )
    )
    public void listenVerifyCode(Map<String,String>map){
        //移除电话，没电话就返回，有电话就发短信
        String phone = map.remove("phone");
        if (phone == null){
            return;
        }

        try {
            smsHelper.sendMessage(phone,prop.getSignName(),
                    prop.getVerifyCodeTemplate(),
                    JsonUtils.toString(map));
        } catch (LyException e) {
            log.error("【SMS服务】短信验证码发送失败", e);
        }
    }


}
